require(['init'], function() {

  var classuid = location.search.urlToObj().classuid;
  var studentUrl;

  if (!classuid) {
    return;
  } else {
    $('#J_classinfo')[0].href += '?classuid=' + classuid;
    $('#J_lessoninfo')[0].href += '?classuid=' + classuid;
    $('.breadcrumb .active a').text(i18next.t('table.compileclass')).attr('href', 'javascript:void(0)')
  }


  var classFullData = {
    classInfo: false,
    lessonList: false,
    studentList: false,
    auditList: false,
    classTypes: false
  }

  function fullDataReady() {
    var loaded = true;
    $.each(classFullData, function(key, value) {
      if (value === false) {
        return loaded = false
      }
    })

    if (loaded) {
      readyCallback(classFullData)
    }
  }

  function getClassTypes(cb) {
    ajaxMethod({
      url: '/api/eeo/classtypes',
      success: function(data, status) {
        if (status.code == 0) {
          cb && cb(data)
        }
      }
    })
  }

  /**
   * [LessonCreator description]
   * @param {[type]} options [description]
   */
  function LessonCreator(options) {
    options = options || {};
    this.data = options.data || this.getDefaultData();
    this.$dom = $('<div class="formList"></div>');

    this.init(this.configList);
  }

  LessonCreator.prototype = {
    configList: [{
        title: i18next.t('table.coursename'),
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.$lessonName = $('<input class="form-control" data-formcheck="length" style="width: 300px;" />').appendTo($content);
            lessonCreator.$lessonName.on('change', function() {
              lessonCreator.data.lessonName = $.trim(lessonCreator.$lessonName.val());
            })
          },
          update: function($content, lessonCreator, formData) {
            lessonCreator.$lessonName.val(formData.lessonName).change();
          }
        }
      },
      {
        title: i18next.t('table.start'),
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.lessonStartDateInput = new DateInput();
            lessonCreator.lessonStartDateInput.$dom.appendTo($content);
            lessonCreator.lessonStartDateInput.$dom.on('change', function() {
              lessonCreator.calcLessonTime();
            });
          },
          update: function($content, lessonCreator, formData) {
            var startDayStr = new Date(formData.startTime).Format('YYYY-MM-DD');
            lessonCreator.lessonStartDateInput.minDate(startDayStr);
            lessonCreator.lessonStartDateInput.value(startDayStr);
          }
        }
      },
      {
        title: i18next.t('table.opentime'),
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.lessonStartTimeInput = new TimeInput();
            var lessonStartDate = new Date(lessonCreator.data.startTime);
            lessonCreator.lessonStartTimeInput.value(lessonStartDate.getHours(), lessonStartDate.getMinutes());
            lessonCreator.lessonStartTimeInput.$dom.appendTo($content);

            lessonCreator.lessonStartTimeInput.$dom.on('change', 'input', function() {
              lessonCreator.calcLessonTime();
            });

          },

        }
      },
      {
        title: i18next.t('table.lessonduration'),
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.lessonDurationSelector = new LessonDurationSelector();
            lessonCreator.lessonDurationSelector.$dom.appendTo($content);
            lessonCreator.lessonDurationSelector.$dom.on('change', 'input', function() {
              lessonCreator.calcLessonTime();
            });
          },
          update: function($content, lessonCreator, formData) {
            var lessonDurationTime = formData.endTime - formData.startTime;
            lessonCreator.lessonDurationSelector.setValue(lessonDurationTime);
          }
        }
      },
      {
        title: i18next.t('table.teacher'), //lessonCreator.studentListViewer
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.$lessonHeadTeacherBtn = $('<a class="btn btn-primary baseWidth" data-formcheck="length"><span class="icon icon-size-16 icon-btn-plus"></span>&nbsp;' + i18next.t('table.chooseteacher') + '</a>').appendTo($content);
            lessonCreator.instructorListViewer = new ContactViewList({
              userType: 'teacher',
              hasAvatar: true,
              editable: false
            });
            lessonCreator.instructorListViewer.$dom.addClass('inline-block').hide().appendTo($content);


            lessonCreator.checkedTeacherDataList = {};
            lessonCreator.teacherSelect = function() {
              ajaxMethod({
                url: '/api/teachers',
                success: function(data) {
                  var candidateTeacherList = {}
                  $.each(data, function(i, item) {
                    candidateTeacherList[item.teacheruid] = {
                      id: item.teacheruid,
                      avatar: item.photo || 'img/avatar.png',
                      name: item.lastname,
                      phone: item.ClassInNo
                    }
                  })


                  var teacherSelector = new ContactSelector({
                    candidateDataList: candidateTeacherList,
                    checkedDataList: lessonCreator.checkedTeacherDataList,
                    checkedMax: 1,
                    searchIntervalTime: 1000,
                    callback: {
                      searchChange: function(seachInputValue) {
                        if (seachInputValue === '') {
                          teacherSelector.candidateList.update(candidateTeacherList);
                        } else {
                          // initConfig.inSearch=true;
                          function getTeacherList(query, cb) {
                            ajaxMethod({
                              url: '/api/teachers',
                              data: query || {},
                              success: function(data) {
                                cb && cb(data)
                              }
                            })
                          }

                          getTeacherList({
                              querystr: seachInputValue
                            },
                            function(data) {
                              var candidateTeacherList = {}
                              $.each(data.list, function(i, item) {
                                candidateTeacherList[item.teacheruid] = {
                                  id: item.teacheruid,
                                  avatar: item.photo || '../img/avatar.png',
                                  name: item.lastname,
                                  phone: item.ClassInNo
                                }
                              })

                              teacherSelector.candidateList.update(candidateTeacherList)
                            }
                          )
                        }
                      },
                      submit: function(checkedDataList) {
                        if (!Object.keys(checkedDataList).length) {
                          _Tips(i18next.t('table.pleaseselect'));
                          return false;
                        }

                        lessonCreator.checkedTeacherDataList = checkedDataList;

                        var checkedTeacherData;
                        for (var key in checkedDataList) {
                          if (checkedDataList.hasOwnProperty(key)) {
                            checkedTeacherData = checkedDataList[key];
                          }
                        }

                        lessonCreator.data.instructor = checkedTeacherData;
                        lessonCreator.$lessonHeadTeacherBtn.html(lessonCreator.data.instructor.name).attr('data-value', lessonCreator.data.instructor.id).hide();
                        lessonCreator.instructorListViewer.update(checkedDataList);
                        lessonCreator.instructorListViewer.$dom.show().addClass('cursor-pointer');
                        FormCheck.inputCheck(lessonCreator.$lessonHeadTeacherBtn);
                        /*
                        console.log(checkedDataList);
                        $addTeacherBtn.hide()

                        teacherViewList.update(checkedDataList)*/
                      }
                    }
                  })
                  teacherSelector.popUpBox.show();
                }
              })
            }

            lessonCreator.$lessonHeadTeacherBtn.on('click', function() {
              lessonCreator.teacherSelect();
            });

            lessonCreator.instructorListViewer.$dom.on('click', function() {
              lessonCreator.teacherSelect();
            });
          },

        }
      },
      {
        title: i18next.t('table.attendance'), //上台人数
        content: {
          init: function($content, lessonCreator) {
            var classTypes = $.map(classFullData.classTypes, function(item) {
              return {
                dataValue: item.id,
                context: item.name
              }
            })

            lessonCreator.seatNumInput = new SelectInput({
              inputStyle: {
                width: 100
              },
              optionList: classTypes,
              selected: classTypes.length,
              onChange: function() {
                lessonCreator.data.classTypeId = lessonCreator.seatNumInput.value();
              }
            })
            lessonCreator.seatNumInput.$dom.appendTo($content);
          },
          update: function($content, lessonCreator, formData) {
            lessonCreator.seatNumInput.value(formData.classTypeId);
          }
        }
      },
      {
        title: i18next.t('table.classresources'), //课节资源
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.cloudFileInput = new CloudFileInput({
              selectorMode: 'normal',
              callback: {
                done: function(folderData) {
                  lessonCreator.data.cloudFolderId = folderData.id;
                  lessonCreator.data.cloudFolderPathStr = folderData.pathStr;
                }
              }
            });
            lessonCreator.cloudFileInput.$dom.appendTo($content);
            lessonCreator.cloudFileInput.$dom.on('click', function() {
              // listForm.popUpBox.$content.scrollTop(100);
            });
          },
          update: function($content, lessonCreator, formData) {
            lessonCreator.cloudFileInput.setValue(formData.cloudFolderId, formData.cloudFolderPathStr);
          }
        }
      },
      {
        title: i18next.t('table.webcaststatus'),
        content: {
          init: function($content, lessonCreator) {

            $content.addClass('content-size-16');
            lessonCreator.recordCheckBtn = new CheckBtn({
              inputName: 'webcastRecord',
              labelText: i18next.t('table.recordlesson') //录课
            });
            lessonCreator.recordCheckBtn.$dom.appendTo($content);

            lessonCreator.liveCheckBtn = new CheckBtn({
              inputName: 'webcastLive',
              disabled: true,
              labelText: i18next.t('table.live') //直播
            });
            lessonCreator.liveCheckBtn.$dom.appendTo($content);

            lessonCreator.replayCheckBtn = new CheckBtn({
              inputName: 'webcastReplay',
              disabled: true,
              labelText: i18next.t('table.playback') //回放
            });
            lessonCreator.replayCheckBtn.$dom.appendTo($content);

            lessonCreator.checkRecord = function() {
              var recordOpen = lessonCreator.recordCheckBtn.checked();
              if (recordOpen) {
                lessonCreator.liveCheckBtn.disabled(false);
                lessonCreator.replayCheckBtn.disabled(false);
              } else {
                lessonCreator.liveCheckBtn.checked(false);
                lessonCreator.replayCheckBtn.checked(false);
                lessonCreator.liveCheckBtn.disabled(true);
                lessonCreator.replayCheckBtn.disabled(true);
              }
            }
            lessonCreator.userCheckedStatus = function() {
              lessonCreator.data.castinfo.record = lessonCreator.recordCheckBtn.checked();
              lessonCreator.data.castinfo.live = lessonCreator.liveCheckBtn.checked();
              lessonCreator.data.castinfo.replay = lessonCreator.replayCheckBtn.checked();
            }

            lessonCreator.recordCheckBtn.$input.on('change', function() {
              lessonCreator.checkRecord();
              lessonCreator.userCheckedStatus();
            });
            lessonCreator.liveCheckBtn.$input.on('change', function() {
              lessonCreator.userCheckedStatus();
            });
            lessonCreator.replayCheckBtn.$input.on('change', function() {
              lessonCreator.userCheckedStatus();
            });

          },
          update: function($content, lessonCreator, formData) {
            lessonCreator.recordCheckBtn.checked(formData.castinfo.record);
            lessonCreator.liveCheckBtn.checked(formData.castinfo.live);
            lessonCreator.replayCheckBtn.checked(formData.castinfo.replay);
          }
        }
      }
    ],

    constructor: LessonCreator,

    getDefaultData: function() {
      var minStartDelayTime = 5 * 60 * 1000;
      var lessonDefaultStartTime = Math.ceil(new Date().getTime() / minStartDelayTime) * minStartDelayTime + minStartDelayTime;
      var lessonData = {
        lessonName: classFullData.classInfo.coursename + ' - ' + (classFullData.lessonList.length + 1),
        startTime: lessonDefaultStartTime,
        endTime: (lessonDefaultStartTime + 25 * 60 * 1000),
        instructor: false,
        cloudFolderId: classFullData.classInfo.folderid,
        cloudFolderPathStr: classFullData.classInfo.foldername,
        classTypeId: classFullData.classTypes.length,
        castinfo: {
          record: false,
          live: false,
          replay: false
        }
      };
      return lessonData;
    },

    createFormLi: function(liConfig) {
      var $formLi = $('<div class="formLi"></div>').appendTo(this.$dom);
      $('<div class="formTitle"></div>').html('<span class="titleText">' + liConfig.title + '</span>').appendTo($formLi);
      var $formContent = $('<div class="formContent"></div>').appendTo($formLi);
      liConfig.content.init($formContent, this);
      if (liConfig.content.update) {
        liConfig.content.update($formContent, this, this.data);
      }
    },

    init: function(liConfigList) {
      $.each(liConfigList, function(i, cur) {
        this.createFormLi(cur)
      }.bind(this));

    },

    calcLessonTime: function() {
      var newStartDateTime = new Date(this.lessonStartDateInput.value() + ' 00:00').getTime();
      var newStartHourTime = this.lessonStartTimeInput.value() * 1;
      var newStartTime = newStartDateTime + newStartHourTime;
      var newEndTime = newStartTime + this.lessonDurationSelector.value();
      this.data.startTime = newStartTime;
      this.data.endTime = newEndTime;
    }
  }

  /**
   * [LessonBatchCreator description]
   * @param {[type]} options [description]
   */
  function LessonBatchCreator(options) {
    options = options || {};
    this.data = options.data || this.getDefaultData();
    this.$dom = $('<div class="formList"></div>');

    this.init(this.configList);
  }

  LessonBatchCreator.prototype = {
    configList: [{
        title: i18next.t('table.coursename'), //课程名称
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.$lessonName = $('<input class="form-control" data-formcheck="length" style="width: 300px;" />').appendTo($content);
            lessonCreator.$lessonName.on('change', function() {
              lessonCreator.data.lessonName = $.trim(lessonCreator.$lessonName.val());
            })

            $content.append('&nbsp;-&nbsp;');
            lessonCreator.lessonNameSuffixInput = new NumberInput({
              minValue: 0,
              inputStyle: {
                width: 50
              }
            });
            lessonCreator.lessonNameSuffixInput.$input.on('change', function() {
              lessonCreator.data.lessonSn = lessonCreator.lessonNameSuffixInput.val();
            });
            lessonCreator.lessonNameSuffixInput.$dom.appendTo($content);
          },
          update: function($content, lessonCreator, formData) {
            lessonCreator.$lessonName.val(formData.lessonName);
            lessonCreator.lessonNameSuffixInput.value(formData.lessonSn);
          }
        }
      },
      {
        title: i18next.t('table.coursesize'), //课节数量
        content: {
          init: function($content, lessonCreator) {

            lessonCreator.lessonAddNumInput = new NumberInput({
              minValue: 2,
              maxValue: 300,
              inputStyle: {
                width: 80
              }
            });

            lessonCreator.lessonAddNumInput.$dom.addClass('baseWidth_2').appendTo($content);
            $content.append('&nbsp;' + i18next.t('table.section') + '');

            lessonCreator.lessonAddNumInput.$input.on('change', function() {
              lessonCreator.data.batchNum = lessonCreator.lessonAddNumInput.value();
            });
          },
          update: function($content, lessonCreator, formData) {
            lessonCreator.lessonAddNumInput.value(formData.batchNum);
          }
        }
      },
      {
        title: i18next.t('table.start'), //开课日期
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.lessonStartDateInput = new DateInput();
            lessonCreator.lessonStartDateInput.$dom.appendTo($content);
            lessonCreator.lessonStartDateInput.$dom.on('change', function() {
              lessonCreator.calcLessonTime();
            });
          },
          update: function($content, lessonCreator, formData) {
            var startDayStr = new Date(formData.startTime).Format('YYYY-MM-DD');
            lessonCreator.lessonStartDateInput.minDate(startDayStr);
            lessonCreator.lessonStartDateInput.value(startDayStr);
          }
        }
      },
      {
        title: i18next.t('table.opentime'), //开课时间
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.lessonStartTimeInput = new TimeInput();
            var lessonStartDate = new Date(lessonCreator.data.startTime);
            lessonCreator.lessonStartTimeInput.value(lessonStartDate.getHours(), lessonStartDate.getMinutes());
            lessonCreator.lessonStartTimeInput.$dom.appendTo($content);

            lessonCreator.lessonStartTimeInput.$dom.on('change', 'input', function() {
              lessonCreator.calcLessonTime();
            });

          },

        }
      },
      {
        title: i18next.t('table.lessonduration'), //课节时长
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.lessonDurationSelector = new LessonDurationSelector();
            lessonCreator.lessonDurationSelector.$dom.appendTo($content);
            lessonCreator.lessonDurationSelector.$dom.on('change', 'input', function() {
              lessonCreator.calcLessonTime();
            });
          },
          update: function($content, lessonCreator, formData) {
            var lessonDurationTime = formData.endTime - formData.startTime;
            lessonCreator.lessonDurationSelector.setValue(lessonDurationTime);
          }
        }
      },
      {
        title: i18next.t('table.classrules'), //上课规律
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.weekdayCheckBtnGroup = new WeekdayCheckBtnGroup({
              onChange: function() {
                lessonCreator.data.dayLaw = lessonCreator.weekdayCheckBtnGroup.value();
              }
            });
            lessonCreator.weekdayCheckBtnGroup.$dom.appendTo($content);
          },
          update: function($content, lessonCreator, formData) {
            if (formData.dayLaw) {
              lessonCreator.weekdayCheckBtnGroup.value(formData.dayLaw);
            }
          }
        }
      },
      {
        title: i18next.t('table.teacher'), //lessonCreator.studentListViewer  授课教师
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.$lessonHeadTeacherBtn = $('<a class="btn btn-primary baseWidth" data-formcheck="length"><span class="icon icon-size-16 icon-btn-plus"></span>&nbsp;' + i18next.t('table.chooseteacher') + '</a>').appendTo($content);
            lessonCreator.instructorListViewer = new ContactViewList({
              userType: 'teacher',
              hasAvatar: true,
              editable: false
            });
            lessonCreator.instructorListViewer.$dom.addClass('inline-block').hide().appendTo($content);


            lessonCreator.checkedTeacherDataList = {};
            lessonCreator.teacherSelect = function() {
              ajaxMethod({
                url: '/api/teachers',
                success: function(data) {
                  var candidateTeacherList = {}
                  $.each(data, function(i, item) {
                    candidateTeacherList[item.teacheruid] = {
                      id: item.teacheruid,
                      avatar: item.photo || 'img/avatar.png', //item.photo,
                      name: item.lastname,
                      phone: item.ClassInNo
                    }
                  })


                  var teacherSelector = new ContactSelector({
                    candidateDataList: candidateTeacherList,
                    checkedDataList: lessonCreator.checkedTeacherDataList,
                    checkedMax: 1,
                    searchIntervalTime: 1000,
                    callback: {
                      searchChange: function(seachInputValue) {
                        if (seachInputValue === '') {
                          teacherSelector.candidateList.update(candidateTeacherList);
                        } else {
                          // initConfig.inSearch=true;
                          function getTeacherList(query, cb) {
                            ajaxMethod({
                              url: '/api/teachers',
                              data: query || {},
                              success: function(data) {
                                cb && cb(data)
                              }
                            })
                          }

                          getTeacherList({
                              querystr: seachInputValue
                            },
                            function(data) {
                              var candidateTeacherList = {}
                              $.each(data.list, function(i, item) {
                                candidateTeacherList[item.teacheruid] = {
                                  id: item.teacheruid,
                                  avatar: item.photo || '../img/avatar.png',
                                  name: item.lastname,
                                  phone: item.ClassInNo
                                }
                              })

                              teacherSelector.candidateList.update(candidateTeacherList)
                            }
                          )
                        }
                      },
                      submit: function(checkedDataList) {
                        if (!Object.keys(checkedDataList).length) {
                          _Tips(i18next.t('table.pleaseselect'));
                          return false;
                        }

                        lessonCreator.checkedTeacherDataList = checkedDataList;

                        var checkedTeacherData;
                        for (var key in checkedDataList) {
                          if (checkedDataList.hasOwnProperty(key)) {
                            checkedTeacherData = checkedDataList[key];
                          }
                        }

                        lessonCreator.data.instructor = checkedTeacherData;
                        lessonCreator.$lessonHeadTeacherBtn.html(lessonCreator.data.instructor.name).attr('data-value', lessonCreator.data.instructor.id).hide();
                        lessonCreator.instructorListViewer.update(checkedDataList);
                        lessonCreator.instructorListViewer.$dom.show();
                        FormCheck.inputCheck(lessonCreator.$lessonHeadTeacherBtn);
                        /*
                        console.log(checkedDataList);
                        $addTeacherBtn.hide()

                        teacherViewList.update(checkedDataList)*/
                      }
                    }
                  })
                  teacherSelector.popUpBox.show();
                }
              })
            }

            lessonCreator.$lessonHeadTeacherBtn.on('click', function() {
              lessonCreator.teacherSelect();
            });

            lessonCreator.instructorListViewer.$dom.on('click', function() {
              lessonCreator.teacherSelect();
            });
          },
        }
      },
      {
        title: i18next.t('table.attendance'), //上台人数
        content: {
          init: function($content, lessonCreator) {
            var classTypes = $.map(classFullData.classTypes, function(item) {
              return {
                dataValue: item.id,
                context: item.name
              }
            })

            lessonCreator.seatNumInput = new SelectInput({
              inputStyle: {
                width: 100
              },
              optionList: classTypes,
              selected: classTypes.length,
              onChange: function() {
                lessonCreator.data.classTypeId = lessonCreator.seatNumInput.value();
              }
            })
            lessonCreator.seatNumInput.$dom.appendTo($content);
          },
          update: function($content, lessonCreator, formData) {
            lessonCreator.seatNumInput.value(formData.classTypeId);
          }
        }
      },
      {
        title: i18next.t('table.classresources'), //课节资源
        content: {
          init: function($content, lessonCreator) {
            lessonCreator.cloudFileInput = new CloudFileInput({
              selectorMode: 'normal',
              callback: {
                done: function(folderData) {
                  lessonCreator.data.cloudFolderId = folderData.id;
                  lessonCreator.data.cloudFolderPathStr = folderData.pathStr;
                }
              }
            });
            lessonCreator.cloudFileInput.$dom.appendTo($content);
            lessonCreator.cloudFileInput.$dom.on('click', function() {
              // listForm.popUpBox.$content.scrollTop(100);
            });
          },
          update: function($content, lessonCreator, formData) {
            lessonCreator.cloudFileInput.setValue(formData.cloudFolderId, formData.cloudFolderPathStr);
          }
        }
      },
      {
        title: '',
        content: {
          init: function($content, lessonCreator) {

            $content.addClass('content-size-16');
            lessonCreator.recordCheckBtn = new CheckBtn({
              inputName: 'webcastRecord',
              labelText: i18next.t('table.recordlesson') //录课
            });
            lessonCreator.recordCheckBtn.$dom.appendTo($content);

            lessonCreator.liveCheckBtn = new CheckBtn({
              inputName: 'webcastLive',
              disabled: true,
              labelText: i18next.t('table.live') //直播
            });
            lessonCreator.liveCheckBtn.$dom.appendTo($content);

            lessonCreator.replayCheckBtn = new CheckBtn({
              inputName: 'webcastReplay',
              disabled: true,
              labelText: i18next.t('table.playback') //回放
            });
            lessonCreator.replayCheckBtn.$dom.appendTo($content);

            lessonCreator.checkRecord = function() {
              var recordOpen = lessonCreator.recordCheckBtn.checked();
              if (recordOpen) {
                lessonCreator.liveCheckBtn.disabled(false);
                lessonCreator.replayCheckBtn.disabled(false);
              } else {
                lessonCreator.liveCheckBtn.checked(false);
                lessonCreator.replayCheckBtn.checked(false);
                lessonCreator.liveCheckBtn.disabled(true);
                lessonCreator.replayCheckBtn.disabled(true);
              }
            }
            lessonCreator.userCheckedStatus = function() {
              lessonCreator.data.castinfo.record = lessonCreator.recordCheckBtn.checked();
              lessonCreator.data.castinfo.live = lessonCreator.liveCheckBtn.checked();
              lessonCreator.data.castinfo.replay = lessonCreator.replayCheckBtn.checked();
            }

            lessonCreator.recordCheckBtn.$input.on('change', function() {
              lessonCreator.checkRecord();
              lessonCreator.userCheckedStatus();
            });
            lessonCreator.liveCheckBtn.$input.on('change', function() {
              lessonCreator.userCheckedStatus();
            });
            lessonCreator.replayCheckBtn.$input.on('change', function() {
              lessonCreator.userCheckedStatus();
            });

          },
          update: function($content, lessonCreator, formData) {
            lessonCreator.recordCheckBtn.checked(formData.castinfo.record);
            lessonCreator.liveCheckBtn.checked(formData.castinfo.live);
            lessonCreator.replayCheckBtn.checked(formData.castinfo.replay);
          }
        }
      }
    ],

    constructor: LessonCreator,

    getDefaultData: function() {
      var minStartDelayTime = 5 * 60 * 1000;
      var lessonDefaultStartTime = Math.ceil(new Date().getTime() / minStartDelayTime) * minStartDelayTime + minStartDelayTime;
      var batchNum = classFullData.classInfo.lessonsQty - classFullData.lessonList.length;
      if (batchNum < 0)
        batchNum = 0;
      var lessonData = {
        lessonName: classFullData.classInfo.coursename,
        lessonSn: classFullData.lessonList.length + 1,
        startTime: lessonDefaultStartTime,
        endTime: (lessonDefaultStartTime + 25 * 60 * 1000),
        batchNum: batchNum,
        instructor: false,
        dayLaw: [$.newDate(lessonDefaultStartTime).getDay()],
        cloudFolderId: classFullData.classInfo.folderid,
        cloudFolderPathStr: classFullData.classInfo.foldername,
        classTypeId: classFullData.classTypes.length,
        castinfo: {
          record: false,
          live: false,
          replay: false
        }
      };
      return lessonData;
    },

    createFormLi: function(liConfig) {
      var $formLi = $('<div class="formLi"></div>').appendTo(this.$dom);
      $('<div class="formTitle"></div>').html('<span class="titleText">' + liConfig.title + '</span>').appendTo($formLi);
      var $formContent = $('<div class="formContent"></div>').appendTo($formLi);
      liConfig.content.init($formContent, this);
      if (liConfig.content.update) {
        liConfig.content.update($formContent, this, this.data);
      }
    },
    init: function(liConfigList) {
      $.each(liConfigList, function(i, cur) {
        this.createFormLi(cur)
      }.bind(this));
    },

    calcLessonTime: function() {
      var newStartDateTime = new Date(this.lessonStartDateInput.value() + ' 00:00').getTime();
      var newStartHourTime = this.lessonStartTimeInput.value() * 1;
      var newStartTime = newStartDateTime + newStartHourTime;
      var newEndTime = newStartTime + this.lessonDurationSelector.value();
      this.data.startTime = newStartTime;
      this.data.endTime = newEndTime;
    }
  }

  /**
   * [Lesson description]
   * @param {[type]} options [description]
   */
  function Lesson(options) {

    this.$dom = $('<tr></tr>');
    this.data = options.data;

    this.show();
    this.bindUI();
  }

  Lesson.prototype = {
    constructor: Lesson,

    show: function() {
      var _this = this
      var data = this.data;
      this.$dom.html('');

      this.$dom.append('<td><span>' + data.orderid + '</span></td>');

      this.$lessonname = $('<span class="cursor-edit">' + data.name + '</span>').appendTo($('<td></td>').appendTo(this.$dom));
      this.$begindate = $('<span class="cursor-edit">' + data.begintime.substr(0, 10) + '</span>').appendTo($('<td></td>').appendTo(this.$dom));
      this.$begintime = $('<span class="cursor-edit">' + data.begintime.substr(11, 5) + '</span>').appendTo($('<td></td>').appendTo(this.$dom));
      this.$durationMinute = $('<span class="cursor-edit">' + getDurationMinute(data.begintime, data.endtime) + '' + i18next.t('table.minute') + '</span>').appendTo($('<td></td>').appendTo(this.$dom));

      //teacher
      this.$teacherTd = $('<td style="width: 170px;"></td>').appendTo(this.$dom);
      var teacherDataList = [];
      teacherDataList.push(this.data.teacherInfo)

      this.teacherViewList = new ContactViewList({
        hasAvatar: true,
        dataList: teacherDataList
      })
      this.teacherViewList.$dom.addClass('cursor-pointer');
      this.$teacherTd.html(this.teacherViewList.$dom);


      //student
      this.$studentTd = $('<td style="width: 170px;"></td>').appendTo(this.$dom);
      this.$studentEdit = $('<div class="btn btn-default">' + (data.students.length || 0) + '</div>').appendTo(this.$studentTd);

      //上台人数
      this.$seatNum = $('<td></td>').css('width', 80).appendTo(this.$dom)
      var setNumText = ''
      $.each(classFullData.classTypes, function(i, item) {
        if (item.id == data.classTypeId) {
          setNumText = item.name
          return false
        }
      })
      this.$seatNum.html('<span>' + setNumText + '</span>')

      //cloud
      this.$resourceTd = $('<td class="text-center"></td>').css('width', 140).appendTo(this.$dom);
      this.cloudFileInput = new CloudFileInput({
        selectorMode: 'normal',
        className: 'btn-sm btn-default'
      });
      this.cloudFileInput.$dom.css({
        width: 120,
        maxWidth: 120
      }).appendTo(this.$resourceTd);

      this.cloudFileInput.cloudDiskSelector.popUpBox.callback.yesAfter = function() {
        var postData = {
          folderid: _this.cloudFileInput.cloudDiskSelector.checkedFolderData.id,
          foldername: _this.cloudFileInput.cloudDiskSelector.checkedFolderData.name
        }
        _this.updateLessonData(postData);
      }

      this.cloudFileInput.setValue(data.folderid, data.foldername);

      //webcast
      this.$recordTd = $('<td class="text-center"></td>').css('width', 60).appendTo(this.$dom);
      this.recordStatus = new this.checkedStatus()
      this.recordStatus.$dom.appendTo(this.$recordTd)

      this.$liveTd = $('<td class="text-center"></td>').css('width', 60).appendTo(this.$dom);
      this.liveStatus = new this.checkedStatus()
      this.liveStatus.$dom.appendTo(this.$liveTd)

      this.$replayTd = $('<td class="text-center"></td>').css('width', 60).appendTo(this.$dom);
      this.replayStatus = new this.checkedStatus()
      this.replayStatus.$dom.appendTo(this.$replayTd)

      //delete
      this.$deleteTd = $('<td></td>').appendTo(this.$dom);
      this.$deleteBtn = $('<div class="btn"><span class="icon icon-size-16 icon-delete"></span></div>').appendTo(this.$deleteTd);
    },

    bindUI: function() {
      this.bindTeacherTd();
      this.bindStudentTd();
      this.bindDeleteTd();

      this.bindEditLessonName();
      this.bindEditBeginDate();
      this.bindEditBeginTime();
      this.bindEditDuration();


      this.bindRecord()
      this.bindLive()
      this.bindReplay()
    },

    bindTeacherTd: function() {
      var _this = this;
      var $teacherTd = this.$teacherTd;
      var teacherViewList = this.teacherViewList;

      $teacherTd.on('click', function() {
        ajaxMethod({
          url: '/api/teachers',
          success: function(data) {
            var candidateTeacherList = [];
            $.each(data, function(i, item) {
              candidateTeacherList.push({
                id: item.teacheruid,
                avatar: item.photo || 'img/avatar.png',
                name: item.lastname,
                phone: item.ClassInNo
              });
            })

            var teacherSelector = new ContactSelector({
              candidateDataList: candidateTeacherList,
              checkedDataList: teacherViewList.getDataList(),
              checkedMax: 1,
              callback: {
                submit: function(checkedDataList) {
                  if (!Object.keys(checkedDataList).length) {
                    _Tips(i18next.t('popupbox.pleaseselectteacher')); //请选择教师
                    return false
                  }

                  var teacheruid;
                  $.each(checkedDataList, function(i, v) {
                    teacheruid = v.id;
                  })

                  _this.updateLessonData({
                    teacheruid: teacheruid
                  })
                  // teacherViewList.update(checkedDataList)
                }
              }
            })
            teacherSelector.popUpBox.show();
          }
        })

      })
    },

    bindStudentTd: function() {
      var _this = this;

      var studentList = [];
      var lessonStudentList = [];

      this.$studentEdit.on('click', function() {
        ajaxMethod({
          url: studentUrl,
          success: function(data, status) {
            if (status.code == 0) {
              studentList = data
            }
            ajaxMethod({
              url: '/api/lesson/' + _this.data.scheduleid + '/students',
              success: function(data, status) {
                if (status.code == 0) {
                  lessonStudentList = data
                }

                var candidateStudentList = [];
                $.each(studentList, function(i, item) {
                  candidateStudentList.push({
                    id: item.studentuid,
                    phone: item.ClassInNo,
                    name: item.name,
                    avatar: item.photo
                  })
                })

                var checkedStudentList = [];
                $.each(lessonStudentList, function(i, item) {
                  checkedStudentList.push({
                    id: item.studentuid,
                    phone: item.ClassInNo,
                    name: item.name,
                    avatar: item.photo
                  })
                })

                var studentSelector = new ContactSelector({
                  candidateDataList: candidateStudentList,
                  checkedDataList: checkedStudentList,
                  hideAvatar: true,
                  checkedMax: classFullData.classInfo.quotas,
                  callback: {
                    submit: function(checkedDataList) {
                      if (!Object.keys(checkedDataList).length) {
                        _Tips(i18next.t('popupbox.pleaseselect')); //请选择
                        return false
                      }

                      ajaxMethod({
                        url: '/api/lesson/' + _this.data.scheduleid + '/students',
                        method: 'put',
                        data: {
                          classeid: classuid,
                          students: studentSelector.getCheckedIdList(),
                          length: studentSelector.getCheckedIdList().length
                        },
                        success: function(data, status) {
                          if (status.code == 0) {
                            getLessonList(classuid)
                          }
                        }
                      })
                    }
                  }
                })
                studentSelector.popUpBox.show();

              }
            })
          }
        })

      })
    },

    bindDeleteTd: function() {
      var _this = this;
      this.$deleteBtn.on('click', function() {

        var popUpBox = new PopUpBox({
          type: 'dom',
          style: 'default contentScroll',
          submitBtnType: 'confirm',
          titleText: i18next.t('popupbox.systemmessages'),
          show: true,
          content: '<div style="margin-left:27px;margin-top:34px;">' + i18next.t('popupbox.del') + '</div>',
          callback: {
            yes: function() {
              ajaxMethod({
                url: '/api/lesson/' + _this.data.scheduleid,
                method: 'delete',
                success: function(data, status) {
                  if (status.code == 0) {
                    getLessonList(classuid)
                  }else{
                    _Tips(status.message);
                  }
                }
              })
            },
          },
          position: {
            width: 420,
            height: 200
          }
        })
      })
    },

    bindEditLessonName: function() {
      var _this = this;

      this.$lessonname.on('click', function() {

        var beforeVal = _this.data.name;
        var $content = $('<div class="formList">\
          <div class="formLi">\
            <div class="formTitle">\
              <span>' + i18next.t('table.lessonsname') + '</span>\
            </div>\
            <div class="formContent">\
              <input class="form-control" type="text" name="lessonname" value="' + beforeVal + '" style="width:300px;">\
            </div>\
          </div>\
        </div>');
        var $input = $content.find('[name="lessonname"]');

        var popUpBox = new PopUpBox({
          type: 'dom',
          style: 'default',
          submitBtnType: 'confirm',
          titleText: i18next.t('popupbox.edit'), //编辑课节名称
          content: $content,
          show: true,
          callback: {
            'yes': function(e) {
              var curVal = $.trim($input.val());
              if (curVal == beforeVal) {
                _Tips(i18next.t('popupbox.nochange')); //课节名称无变化
                return false;
              }

              if (curVal == '') {
                _Tips(i18next.t('popupbox.lessonnoempty')); //课节名称不能为空
                return false
              }

              _this.data.name = curVal;
              _this.updateLessonData({
                name: curVal
              });

            }
          },
          position: {
            width: 460,
            height: 200
          }
        })
      })
    },

    bindEditBeginTime: function() {
      var _this = this;

      this.$begintime.on('click', function() {

        var date = new Date(_this.data.begintime);
        var $content = $('<div class="formList">\
          <div class="formLi">\
            <div class="formTitle">\
              <span>' + i18next.t('table.opentime') + '</span>\
            </div>\
            <div class="formContent">\
            </div>\
          </div>\
        </div>');

        var timeInput = new TimeInput()
        timeInput.value(date.getHours(), date.getMinutes());
        timeInput.$dom.appendTo($content.find('.formContent'))
        var beforeVal = timeInput.value()

        _this.popUpBox = new PopUpBox({
          type: 'dom',
          style: 'default',
          submitBtnType: 'confirm',
          titleText: i18next.t('popupbox.edittime'), //编辑课节时间
          content: $content,
          show: true,
          callback: {
            yes: function(e) {
              var curVal = timeInput.value();

              var dateTime = new Date(_this.data.begintime).getDayTime()
              var startTime = dateTime + curVal;
              var duration = new Date(_this.data.endtime).getTime() - new Date(_this.data.begintime).getTime();

              if (curVal == beforeVal) {
                _Tips(i18next.t('popupbox.unchanged'));
                return false;
              }

              if (startTime < new Date().getTime() + 5 * 60 * 1000) {
                _Tips(i18next.t('popupbox.delayminute'));
                return false;
              }

              var lessonTimeData = {
                begintime: new Date(startTime).Format('YYYY-MM-DD hh:mm:ss'),
                endtime: new Date(startTime + duration).Format('YYYY-MM-DD hh:mm:ss')
              }

              // _this.updateLessonData(lessonTimeData);

              checkHandle({
                checkList: [
                  $.extend({}, lessonTimeData, {
                    teacheruid: _this.data.teacherInfo.id,
                    scheduleid: _this.data.scheduleid
                  })
                ],
                callback: function() {
                  _this.updateLessonData(lessonTimeData);
                }
              })
              return false
            }
          },
          position: {
            width: 420,
            height: 200
          }
        })
      })
    },
    bindEditBeginDate: function() {
      var _this = this;
      //begintime : "2017-04-15 17:40:00"
      this.$begindate.on('click', function() {

        var beforeVal = new Date(_this.data.begintime).Format('YYYY-MM-DD');
        var $content = $('<div class="formList">\
          <div class="formLi">\
            <div class="formTitle">\
              <span>' + i18next.t('table.start') + '</span>\
            </div>\
            <div class="formContent">\
              <input type="text" class="form-control" data-type="date-input"  data-valuetype="single"  value="' + beforeVal + '">\
            </div>\
          </div>\
        </div>');
        var $input = $content.find('[data-type="date-input"]');

        _this.popUpBox = new PopUpBox({
          type: 'dom',
          style: 'default',
          submitBtnType: 'confirm',
          titleText: i18next.t('popupbox.editdate'),
          content: $content,
          show: true,
          callback: {
            'yes': function(e) {
              var curVal = $input.val()

              var timeStr = new Date(_this.data.begintime).Format('hh:mm:ss')
              var duration = new Date(_this.data.endtime).getTime() - new Date(_this.data.begintime).getTime();
              var startTime = new Date(curVal + ' ' + timeStr).getTime();

              if (curVal == beforeVal) {
                _Tips(i18next.t('popupbox.unchanged'));
                return false;
              }

              if (startTime < new Date().getTime() + 5 * 60 * 1000) {
                _Tips(i18next.t('popupbox.delaystartminute'));
                return false;
              }

              var lessonTimeData = {
                begintime: new Date(startTime).Format('YYYY-MM-DD hh:mm:ss'),
                endtime: new Date(startTime + duration).Format('YYYY-MM-DD hh:mm:ss')
              }

              // _this.updateLessonData(lessonTimeData);

              checkHandle({
                checkList: [
                  $.extend({}, lessonTimeData, {
                    teacheruid: _this.data.teacherInfo.id,
                    scheduleid: _this.data.scheduleid
                  })
                ],
                callback: function() {
                  _this.updateLessonData(lessonTimeData);
                }
              })
              return false
            }
          },
          position: {
            width: 420,
            height: 200
          }
        })
      })
    },

    bindEditDuration: function() {
      var _this = this;
      this.$durationMinute.on('click', function() {

        var date = new Date(_this.data.begintime);
        var $content = $('<div class="formList">\
          <div class="formLi">\
            <div class="formTitle">\
              <span>' + i18next.t('table.lessonduration') + '</span>\
            </div>\
            <div class="formContent">\
            </div>\
          </div>\
        </div>');

        var lessonDurationTime = new Date(_this.data.endtime).getTime() - new Date(_this.data.begintime).getTime();

        var durationSelector = new LessonDurationSelector();
        durationSelector.setValue(lessonDurationTime);
        durationSelector.$dom.appendTo($content.find('.formContent'))
        var beforeVal = durationSelector.value()

        _this.popUpBox = new PopUpBox({
          type: 'dom',
          style: 'default',
          submitBtnType: 'confirm',
          titleText: i18next.t('popupbox.editduration'), //编辑课节时长
          content: $content,
          show: true,
          callback: {
            yes: function(e) {
              var curVal = durationSelector.value();
              var endtime = new Date(_this.data.begintime).getTime() + curVal;

              if (curVal == beforeVal) {
                _Tips(i18next.t('popupbox.unchanged'));
                return false;
              }

              if (curVal < 25 * 60 * 1000) {
                _Tips(i18next.t('popupbox.courseduration'));
                durationSelector.$dom.find('input').focus();
                return false;
              }

              var lessonTimeData = {
                begintime: _this.data.begintime,
                endtime: new Date(endtime).Format('YYYY-MM-DD hh:mm:ss')
              }

              // _this.updateLessonData(lessonTimeData);

              checkHandle({
                checkList: [
                  $.extend({}, lessonTimeData, {
                    teacheruid: _this.data.teacherInfo.id,
                    scheduleid: _this.data.scheduleid
                  })
                ],
                callback: function() {
                  _this.updateLessonData(lessonTimeData);
                }
              })
              return false

            }
          },
          position: {
            width: 420,
            height: 200
          }
        })
      })
    },

    bindRecord: function() {
      var _this = this
      this.recordStatus.checked(this.data.webcastInfo.record)
      if (this.data.disabled) {
        this.recordStatus.$dom.css('cursor', 'not-allowed');
      } else {
        this.recordStatus.$dom.css('cursor', 'pointer');
      }
      this.recordStatus.$dom.on('click', function() {
        _this.webcastChange()
      })
    },
    bindLive: function() {
      var _this = this
      this.liveStatus.checked(this.data.webcastInfo.live)
      if (this.data.disabled) {
        this.liveStatus.$dom.css('cursor', 'not-allowed');
      } else {
        this.liveStatus.$dom.css('cursor', 'pointer');
      }
      this.liveStatus.$dom.on('click', function() {
        _this.webcastChange()
      })
    },
    bindReplay: function() {
      var _this = this
      this.replayStatus.checked(this.data.webcastInfo.replay)
      if (this.data.disabled) {
        this.replayStatus.$dom.css('cursor', 'not-allowed');
      } else {
        this.replayStatus.$dom.css('cursor', 'pointer');
      }
      this.replayStatus.$dom.on('click', function() {
        _this.webcastChange()
      })
    },

    webcastChange: function() {
      var _this = this;
      console.log('webcastChange');
      if (this.data.webcastInfo.record === false && this.data.webcastInfo.disabled() === true) {
        _Tips(i18next.t('popupbox.networkstate'));
        return;
      }

      var content = {}
      content.webcast = false;
      content.$dom = $('<div style="padding:10px 20px;"></div>');

      var webcastBtnGroup = new WebcastCheckBtnGroup({
        changeCallback: function(changedValue) {
          content.webcast = {
            record: changedValue[0],
            live: changedValue[1],
            replay: changedValue[2]
          }
        }
      });
      webcastBtnGroup.value([this.data.webcastInfo.record, this.data.webcastInfo.live, this.data.webcastInfo.replay]);

      if (this.data.webcastInfo.disabled() === true) {
        webcastBtnGroup.recordBtn.disabled(true);
        webcastBtnGroup.liveBtn.disabled(true);
      }

      webcastBtnGroup.$dom.appendTo(content.$dom);

      var $videoBtn = $('<br /><br /><div class="btn btn-default">' + i18next.t('popupbox.videoaddress') + '</div>').appendTo(content.$dom);
      $videoBtn.on('click', function() {
        var $content = $('<textarea class="content" style="padding:10px;height:100%; width:100%;"></textarea>');
        $.each(_this.data.videosite, function(i, item) {
          var value = $content.val()
          value += item;
          $content.val(value + '\r\n')
          // $content.text += '<br />'
        })

        if (!_this.data.videosite.length) {
          $content.append('<div class="text-center">' + i18next.t('popupbox.novideoaddress') + '</div>')
        }

        var popUpBox = new PopUpBox({
          type: 'dom',
          style: 'default autoResize',
          submitBtnType: 'confirm',
          titleText: i18next.t('popupbox.videolist'),
          drag: true,
          show: true,
          content: $content,
          callback: {
            'yes': function(e) {}
          },
          position: {
            width: 800,
            height: 400
          }
        })
      })
      var popUpBox = new PopUpBox({
        type: 'dom',
        style: 'default',
        titleText: i18next.t('popupbox.editstatus'), //编辑 [录课/直播/回放] 状态
        content: content.$dom,
        show: true,
        callback: {
          yes: function() {
            if (!content.webcast) {
              _Tips(i18next.t('popupbox.networkplay'));
              return false;
            }

            var postData = {
              castinfo: {
                record: Number(content.webcast.record),
                live: Number(content.webcast.live),
                replay: Number(content.webcast.replay)
              }
            }

            _this.updateLessonData(postData);

          }
        },
        position: {
          width: 420,
          height: 200
        }
      })


    },
    checkedStatus: function() {
      var status = this
      status.value = false
      status.$dom = $('<span class="icon icon-size-16 icon-checked-false"></span>')
      status.checked = function(newStatus) {
        if (newStatus !== undefined) {
          status.value = newStatus
        } else {
          return status.value
        }

        if (status.value === true) {
          status.$dom.attr('class', 'icon icon-size-16 icon-checked-true')
        } else {
          status.$dom.attr('class', 'icon icon-size-16 icon-checked-false')
        }
        return status;
      }
    },
    updateLessonData: function(lessonItem) {
      var _this = this;
      var data = {
        classeid: classuid
      }

      ajaxMethod({
        url: '/api/lesson/' + _this.data.scheduleid,
        method: 'put',
        data: $.extend(data, lessonItem),
        success: function(data, status) {
          if (status.code == 0) {
            getLessonList(classuid);
            _this.popUpBox.close();
          }
        }
      })
    }

  }

  function CourseUserViewer(options) {
    options = options || {}

    this.$dom = $('<div class="courseMemberViewer courseStudentViewer"></div>');
    this.data = options.data;
    this.options = {
      titleText: '',
      editable: false,
      hasAvatar: false,
      showNum: false,
      emptyTips: '',
      callback: {}
    };

    $.extend(true, this.options, options);

    this.init();
  }

  CourseUserViewer.prototype = {
    init: function() {
      this.render();
      this.bindEvent();
      this.syncUI();
    },
    render: function() {
      this.$listTitle = $('<div class="listTitle"></div>').appendTo(this.$dom)
      this.$listTitle.append('<div class="titleText">' + this.options.titleText + '</div>')

      if (this.options.showNum) {
        this.$titleNumInfo = $('<div class="titleNumInfo"></div>').appendTo(this.$listTitle)
      }

      if (this.options.editable) {
        this.$listTitle.append(
          '<div class="titleBtnList">\
            <div class="btn btn-primary btn-sm btn-inverse">' + i18next.t('table.compile') + '</div>\
          </div>'
        )
        this.$editBtn = this.$listTitle.find('.btn');
      }

      this.viewList = new ContactViewList({
        hasAvatar: this.options.hasAvatar
      });
      this.viewList.$dom.addClass('cursor-pointer').appendTo(this.$dom);

      this.$emptyTips = $('<div class="emptyTips">' + this.options.emptyTips + '</div>').appendTo(this.$dom)
    },
    bindEvent: function() {
      var _this = this;

      if (this.options.editable) {
        this.$editBtn.on('click', function() {
          _this.options.callback.selectData(_this);
        });

        this.viewList.$dom.on('click', function() {
          _this.options.callback.selectData(_this);
        });
      }

    },
    syncUI: function() {

    }
  }

  /**
   * [getClassInfo 获取班级信息]
   * @param  {[type]}   classuid [description]
   * @param  {Function} cb       [description]
   * @return {[type]}            [description]
   */
  function getClassInfo(classuid, cb) {
    ajaxMethod({
      url: '/api/classe/' + classuid,
      success: function(data) {
        cb && cb(data);
      }
    })
  }

  /**
   * [getLessonList 获取课节列表]
   * @param  {[type]}   classuid [description]
   * @param  {Function} cb       [description]
   * @return {[type]}            [description]
   */
  function getLessonList(classuid, cb) {
    ajaxMethod({
      url: '/api/lessons',
      data: {
        classeid: classuid
      },
      success: function(data) {
        var lessonListData = []
        $.each(data, function(i, item) {
          var lessonData = {
            begintime: item.begintime,
            endtime: item.endtime,
            scheduleid: item.scheduleid,
            name: item.name,
            teacherInfo: {
              id: item.teacherinfo.id,
              avatar: item.teacherinfo.avatar,
              phone: item.teacherinfo.ClassInNo,
              name: item.teacherinfo.name
            },
            folderid: item.folderid,
            foldername: item.foldername,
            classTypeId: item.classtypeid,
            students: item.students,
            webcastInfo: {
              record: !!item.castinfo.record,
              live: !!item.castinfo.live,
              replay: !!item.castinfo.replay
            },
            videosite: item.videosite
          }

          lessonData.webcastInfo.disabled = function() {
            return new Date().getTime() > new Date(lessonData.begintime).getTime() - 20 * 60 * 1000
          }
          lessonListData.push(lessonData);
        })


        if (cb) {
          cb(lessonListData);
        } else {
          classFullData.lessonList = lessonListData
        }

        webcastUrlControl(lessonListData)

        var $lessonTbody = $('#J_lesson-tbody').empty();
        $.each(lessonListData, function(i, v) {
          var lesson = new Lesson({
            data: $.extend(v, {
              orderid: i + 1
            })
          });
          $lessonTbody.append(lesson.$dom);
        })
      }
    })
  }

  /**
   * [getCourseStudentList 获取班级下的学生]
   * @param  {[type]}   classuid [description]
   * @param  {Function} cb       [description]
   * @return {[type]}            [description]
   */
  function getCourseStudentList(classuid, cb) {
    ajaxMethod({
      url: '/api/classe/' + classuid + '/student',
      success: function(data) {
        cb && cb(data);
      }
    })
  }

  /**
   * [getCourseAuditList 获取班级下的旁听生]
   * @param  {[type]}   classuid [description]
   * @param  {Function} cb       [description]
   * @return {[type]}            [description]
   */
  function getCourseAuditList(classuid, cb) {
    ajaxMethod({
      url: '/api/classe/' + classuid + '/student',
      data: {
        identity: 2
      },
      success: function(data) {
        cb && cb(data);
      }
    })
  }

  function checkHandle(config) {
    ajaxMethod({
      url: '/api/schedules/check',
      data: {
        checklist: config.checkList
      },
      success: function(data, status) {
        if (status.code == 0) {
          var getItem = false

          $.each(data, function(i, item) {
            if (item.status.code == 2) {
              getItem = item
            }
            if (item.status.code == 1) {
              getItem = item
              return false;
            }
          })

          if (getItem) {
            if (getItem.status.code == 1) {
              _Tips(getItem.status.message)
            } else if (getItem.status.code == 2) {
              var contentText = getItem.status.message.concat(', ' + i18next.t('table.continue') + '?') + '<br />\
                [ ' + getItem.begintime + ' ~ ' + getItem.endtime + ' ]'
              _Confirm('', contentText, config.callback)
            }
            return;
          }
          config.callback && config.callback();
        }
      }
    })
  }

  /**
   * [webcastUrlControl 控制是否显示直播链接]
   * @param  {[type]} lesssonList [description]
   * @return {[type]}             [description]
   */
  function webcastUrlControl(lesssonList) {
    var showUrl = false;
    $.each(lesssonList, function(i, item) {
      if (item.webcastInfo.live || item.webcastInfo.replay) {
        showUrl = true;
        return false
      }
    })

    var webcastUrl = classFullData.classInfo.webcast;
    $('#J_webcasturl').attr('href', webcastUrl).text(webcastUrl)

    if (showUrl) {
      $('#J_webcast').show()
    } else {
      $('#J_webcast').hide()
    }
  }


  getClassInfo(classuid, function(classInfo) {
    classFullData.classInfo = classInfo;
    fullDataReady()
  })
  getClassTypes(function(classTypes) {
    classFullData.classTypes = classTypes
    fullDataReady();
  })
  getLessonList(classuid, function(lessonList) {
    classFullData.lessonList = lessonList;
    fullDataReady()
  })

  getCourseStudentList(classuid, function(studentList) {
    classFullData.studentList = studentList;
    fullDataReady();
  })

  getCourseAuditList(classuid, function(auditList) {
    classFullData.auditList = auditList;
    fullDataReady();
  })



  function readyCallback(classFullData) {

    //courseUid存在，则是从
    studentUrl = '/api/students'
    var courseUid = classFullData.classInfo.courseuid
    if (courseUid != undefined && courseUid != '') {
      studentUrl = '/api/order/classe/' + courseUid + '/students'
    }

    //显示班级名称
    function showClassName(classInfo) {
      $('.breadcrumb').append(
        '<li>\
          <a href="javascript:void(0)">' + classInfo.classname + '</a>\
        </li>'
      );
    }

    showClassName(classFullData.classInfo)
    webcastUrlControl(classFullData.lessonList)

    //lessonlist
    // var $lessonTbody = $('#J_lesson-tbody').empty();
    // $.each(classFullData.lessonList, function(i, item) {
    //   var lesson = new Lesson({
    //     data: $.extend(item, { orderid: i+1})
    //   });
    //   $lessonTbody.append(lesson.$dom);
    // })

    //studentlist
    var courseStudentList = [];
    $.each(classFullData.studentList, function(i, item) {
      courseStudentList.push({
        id: item.studentuid,
        // avatar: item.photo,
        name: item.name,
        phone: item.ClassInNo
      })
    })

    var studentViewer = new CourseUserViewer({
      titleText: i18next.t('table.classstudent'),
      editable: true,
      hasAvatar: false,
      showNum: true,
      emptyTips: i18next.t('table.addclassstudent'),
      callback: {
        selectData: function(rootInstance) {

          ajaxMethod({
            url: studentUrl,
            success: function(data) {
              var candidateStudentList = []

              $.each(data, function(i, item) {
                candidateStudentList.push({
                  id: item.studentuid,
                  avatar: item.photo,
                  name: item.name,
                  phone: item.ClassInNo
                })
              })

              var teacherIdList = $.map(classFullData.lessonList, function(lessonData, i) {
                return lessonData.teacherInfo.id
              });
              var auditIdList = auditViewer.viewList.getIdList().map(function(item) {
                return parseInt(item)
              });

              var studentSelector = new ContactSelector({
                candidateDataList: candidateStudentList,
                checkedDataList: rootInstance.viewList.getDataList(),
                checkedMax: classFullData.classInfo.quotas,
                hideAvatar: true,
                disableListGroup: [{
                    disableInfo: i18next.t('table.yesteacher'), //该帐号已是任课教师
                    disableList: teacherIdList
                  },
                  {
                    disableInfo: i18next.t('table.yesattend'), //该账号已经为旁听
                    disableList: auditIdList
                  }
                ],
                callback: {
                  submit: function(checkedDataList) {
                    var checkedStudentDataList = [];
                    for (var key in checkedDataList) {
                      if (checkedDataList.hasOwnProperty(key)) {
                        checkedStudentDataList.push(checkedDataList[key].id);
                      }
                    }

                    ajaxMethod({
                      url: '/api/classe/' + classuid + '/student',
                      method: 'put',
                      data: {
                        classeid: classuid,
                        students: checkedStudentDataList,
                        length: checkedStudentDataList.length
                      },
                      success: function(data, status) {
                        if (status.code == 0) {
                          var checkedLen = Object.keys(checkedDataList).length;
                          if (checkedLen) {
                            rootInstance.$emptyTips.hide();
                          } else {
                            rootInstance.$emptyTips.show();
                          }
                          rootInstance.viewList.update(checkedDataList);
                          getLessonList(classuid)
                        }
                      }
                    })
                  }
                }
              })
              studentSelector.$titleText.text(i18next.t('table.compileclassstudent')) //编辑班级学生
              studentSelector.popUpBox.show();
            }
          })
        }
      }
    })

    if (courseStudentList.length) {
      studentViewer.$emptyTips.hide()
    }
    studentViewer.viewList.update(courseStudentList);
    $('#J_courseStudent').append(studentViewer.$dom)


    //auditlist
    var courseAudtiList = [];
    $.each(classFullData.auditList, function(i, item) {
      courseAudtiList.push({
        id: item.studentuid,
        // avatar: item.photo,
        name: item.name,
        phone: item.ClassInNo
      })
    })

    var auditViewer = new CourseUserViewer({
      titleText: i18next.t('table.audit'), //旁听
      editable: true,
      hasAvatar: false,
      showNum: true,
      emptyTips: i18next.t('table.noattend'), //暂无旁听成员
      callback: {
        selectData: function(rootInstance) {
          ajaxMethod({
            url: '/api/students',
            success: function(data) {
              var candidateStudentList = []
              $.each(data, function(i, item) {
                candidateStudentList.push({
                  id: item.studentuid,
                  avatar: item.photo,
                  name: item.name,
                  phone: item.ClassInNo
                })
              })

              var teacherIdList = $.map(classFullData.lessonList, function(lessonData, i) {
                return lessonData.teacherInfo.id
              });
              var studentIdList = studentViewer.viewList.getIdList().map(function(item) {
                return parseInt(item)
              });

              var studentSelector = new ContactSelector({
                candidateDataList: candidateStudentList,
                checkedDataList: rootInstance.viewList.getDataList(),
                checkedMax: 20,
                hideAvatar: true,
                disableListGroup: [{
                    disableInfo: i18next.t('table.yesteacher'), //该帐号已是任课教师
                    disableList: teacherIdList
                  },
                  {
                    disableInfo: i18next.t('table.yesstudent'), //该账号已是班级学生
                    disableList: studentIdList
                  }
                ],
                callback: {
                  submit: function(checkedDataList) {
                    var checkedStudentDataList = [];
                    for (var key in checkedDataList) {
                      if (checkedDataList.hasOwnProperty(key)) {
                        checkedStudentDataList.push(checkedDataList[key].id);
                      }
                    }

                    ajaxMethod({
                      url: '/api/classe/' + classuid + '/student',
                      method: 'put',
                      data: {
                        identity: 2,
                        classeid: classuid,
                        students: checkedStudentDataList,
                        length: checkedStudentDataList.length
                      },
                      success: function(data, status) {
                        if (status.code == 0) {
                          var checkedLen = Object.keys(checkedDataList).length;
                          if (checkedLen) {
                            rootInstance.$emptyTips.hide();
                          } else {
                            rootInstance.$emptyTips.show();
                          }

                          rootInstance.viewList.update(checkedDataList);
                        }
                      }
                    })
                  }
                }
              })
              studentSelector.$titleText.text(i18next.t('table.compileattendstudent')) //编辑旁听学生
              studentSelector.popUpBox.show();
            }
          })
        }
      }
    })

    if (courseAudtiList.length) {
      auditViewer.$emptyTips.hide()
    }
    auditViewer.viewList.update(courseAudtiList);
    $('#J_courseAudit').append(auditViewer.$dom)

    $('#J_addLesson').on('click', function() {
      var lessonCreator = new LessonCreator();
      var popUpBox = new PopUpBox({
        type: 'dom',
        style: 'default contentScroll',
        submitBtnType: 'confirm',
        titleText: i18next.t('popupbox.pleaseselect'),
        drag: true,
        show: true,
        content: lessonCreator.$dom,
        callback: {
          yes: function(e) {
            console.log(lessonCreator.data);
            var lessonData = lessonCreator.data;

            if (lessonData.startTime < new Date().getTime() + 60 * 1000) {
              _Tips(i18next.t('popupbox.lessonstart')); //课节开始时间必须晚于当前时间一分钟以上
              return false;
            }

            var dtime = lessonData.endTime - lessonData.startTime
            if (dtime < 25 * 60 * 1000) {
              _Tips(i18next.t('popupbox.courseduration')); //课程时长至少要25分钟
              return false;
            }

            var formCheckResult = FormCheck.childrenInputCheck(lessonCreator.$dom);
            if (formCheckResult) {
              var postData = {
                classeid: classuid,
                name: lessonData.lessonName,
                begintime: new Date(lessonData.startTime).Format('YYYY-MM-DD hh:mm'),
                endtime: new Date(lessonData.endTime).Format('YYYY-MM-DD hh:mm'),
                teacheruid: lessonCreator.instructorListViewer.getIdList()[0],
                folderid: lessonData.cloudFolderId,
                foldername: lessonData.cloudFolderPathStr,
                classtypeid: lessonData.classTypeId,
                castinfo: {
                  record: Number(lessonData.castinfo.record),
                  live: Number(lessonData.castinfo.live),
                  replay: Number(lessonData.castinfo.replay)
                }
              };
              checkHandle({
                checkList: [{
                  teacheruid: postData.teacheruid,
                  begintime: postData.begintime,
                  endtime: postData.endtime
                }],
                callback: function() {
                  ajaxMethod({
                    url: '/api/lesson',
                    data: {
                      lessons: [postData]
                    },
                    method: 'post',
                    success: function(data, status) {
                      if (status.code == 0) {
                        getLessonList(classuid);
                        popUpBox.close();
                      } else {
                        _Tips(status.message)
                      }
                    }
                  })
                }
              })
            }
            return false;
          }
        },
        position: {
          width: 750,
          height: 490
        }
      })
    })

    $('#J_addLessonBatch').on('click', function() {
      var lessonBatchCreator = new LessonBatchCreator();
      var popUpBox = new PopUpBox({
        type: 'dom',
        style: 'default contentScroll',
        submitBtnType: 'confirm',
        titleText: i18next.t('popupbox.pleaseselect'), //请选择
        drag: true,
        show: true,
        content: lessonBatchCreator.$dom,
        callback: {
          yes: function(e) {
            var lessonData = lessonBatchCreator.data;

            if (lessonData.startTime < new Date().getTime() + 60 * 1000) {
              _Tips(i18next.t('popupbox.lessonstart')); //课节开始时间必须晚于当前时间一分钟以上
              return false;
            }

            var dtime = lessonData.endTime - lessonData.startTime
            if (dtime < 25 * 60 * 1000) {
              _Tips(i18next.t('popupbox.courseduration')); //课程时长至少要25分钟
              return false;
            }

            if (lessonData.dayLaw.length < 1) {
              _Tips(i18next.t('popupbox.classrule')); //请选择上课时间规律
              return false;
            }

            function calcAllLessonData() {
              var list = [],
                sn = 1,
                len = lessonData.batchNum,
                dayLaw = lessonData.dayLaw;
              var firstLessonData = {
                lessonName: lessonData.lessonName + ' - ' + lessonData.lessonSn,
                startTime: lessonData.startTime,
                endTime: lessonData.endTime,
                instructor: $.extend(true, {}, lessonData.instructor),
                cloudFolderId: lessonData.cloudFolderId,
                // seatNum			:lessonData.seatNum,
                castinfo: {
                  record: Number(lessonData.castinfo.record),
                  live: Number(lessonData.castinfo.live),
                  replay: Number(lessonData.castinfo.replay)
                }
              }
              list.push(firstLessonData);

              function getNextLessonDelayTime(timeNum) {
                var dayNow = $.newDate(timeNum).getDay();
                var delayTime = 0;
                $.each(dayLaw, function(i, v) {
                  if (v > dayNow) {
                    delayTime = (v - dayNow) * 86400000;
                    return false;
                  }
                });
                if (delayTime === 0) {
                  delayTime = (dayLaw[0] + 7 - dayNow) * 86400000;
                }
                return delayTime;
              }

              function addNextLessonData() {
                var listLen = list.length;
                var lastLessonData = list[listLen - 1];
                var addLessonData = {};
                var delayTime = getNextLessonDelayTime(lastLessonData.startTime);
                addLessonData = {
                  lessonName: lessonData.lessonName + ' - ' + (lessonData.lessonSn + listLen),
                  startTime: lastLessonData.startTime + delayTime,
                  endTime: lastLessonData.endTime + delayTime,
                  instructor: $.extend(true, {}, lessonData.instructor),
                  cloudFolderId: lessonData.cloudFolderId,
                  classTypeId: lessonData.classTypeId,
                  castinfo: {
                    record: Number(lessonData.castinfo.record),
                    live: Number(lessonData.castinfo.live),
                    replay: Number(lessonData.castinfo.replay)
                  }
                };
                list.push(addLessonData);
              }
              for (; sn < len; sn++) {
                addNextLessonData();
              }
              return list;
            }

            var formCheckResult = FormCheck.childrenInputCheck(lessonBatchCreator.$dom);
            if (formCheckResult) {
              var lessonListData = calcAllLessonData();
              var postLessonListData = []
              $.each(lessonListData, function(i, item) {
                postLessonListData.push({
                  classeid: classuid,
                  name: item.lessonName,
                  begintime: new Date(item.startTime).Format('YYYY-MM-DD hh:mm'),
                  endtime: new Date(item.endTime).Format('YYYY-MM-DD hh:mm'),
                  teacheruid: lessonBatchCreator.instructorListViewer.getIdList()[0],
                  folderid: lessonData.cloudFolderId,
                  foldername: lessonData.cloudFolderPathStr,
                  classtypeid: lessonData.classTypeId,
                  castinfo: {
                    record: Number(lessonData.castinfo.record),
                    live: Number(lessonData.castinfo.live),
                    replay: Number(lessonData.castinfo.replay)
                  }
                })
              })

              var checkList = [];
              $.each(postLessonListData, function(i, item) {
                checkList.push({
                  teacheruid: postLessonListData[i].teacheruid,
                  begintime: postLessonListData[i].begintime,
                  endtime: postLessonListData[i].endtime
                })
              })

              checkHandle({
                checkList: checkList,
                callback: function() {
                  ajaxMethod({
                    url: '/api/lesson',
                    data: {
                      lessons: postLessonListData
                    },
                    method: 'post',
                    success: function(data, status) {
                      if (status.code == 0) {
                        getLessonList(classuid);
                        popUpBox.close();
                      }
                    }
                  })
                }
              })

            }
            return false;
          }
        },
        position: {
          width: 750,
          height: 490
        }
      })
    })
  }

})
